/**
 * 选择商品分类
 */
var zTree1 = null;
$(document).ready(
	function(){
	$("#categoryTree").height($(window).height());	
	zTree1 = $.fn.zTree.init($("#categoryDemo"), setting);
});
var setting = {
	async: {
		enable: true,
		url: base + "/admin/b2c/goodsCategory/treeData.jhtml",
		autoParam: ["id=parentId"]
	},
	edit:{
		enable: true,
		showRemoveBtn: setRemoveBtn,
		showRenameBtn: false,
		removeTitle: "删除"
	},
	data: {
		simpleData: {
			enable: true
		}
	},
	callback: {
		beforeRemove: function(treeId, treeNode) {

			if(window.parent.frames["rightFrame"].confirm("你确定删除("+treeNode.name+")节点吗？")){
				var rightFrame = window.parent.frames["rightFrame"];
				if(treeNode.isParent) {
					rightFrame.LG.showError('该分类存在子分类，不能执行删除操作');
					return  false;
				} else {
					var flag = true;
					$.ajax({
						url: base + "/admin/b2c/goodsCategory/delete.jhtml",
						type:"POST",
						async:false,
						data:{ids:treeNode.id},
						error: function (xhr){
							flag = false;
							if(xhr.status == 403){
								rightFrame.LG.showError('您无权进行此项操作');
							}else if(xhr.status == 400){
								var responseError = JSON.parse(xhr.responseText);
								var info = '';
								for(var i = 0;i < responseError.errors.length;i++){
									info += responseError.errors[i] + '<br/>';
								}
								rightFrame.LG.showError(info);
							}else{
								rightFrame.LG.showError('发现系统错误 <BR>错误码：' + xhr.status);
							}
						}
					});
					return flag;
				}
			}
			return false;
		},
		onClick: clickNode,
		onRemove: onRemove,
		onAsyncSuccess: zTreeOnAsyncSuccess
	}
};

function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
	var zTree = $.fn.zTree.getZTreeObj(treeId);
	var nodes = zTree.getNodes();
	zTree.expandNode(nodes[0], true);
}

function onRemove(e, treeId, treeNode) {
	var rightFrame = window.parent.frames["rightFrame"];
	rightFrame.LG.tip('删除成功');
}
/**
 * 父节点不现实删除按钮
 * @param treeId
 * @param treeNode
 * @returns {boolean}
 */
function setRemoveBtn(treeId, treeNode) {
	return !treeNode.isParent;
}
//选中事件处理
function clickNode(event, treeId, treeNode, clickFlag){
	var url;
	if(treeNode.id){
		url = base + "/admin/b2c/goodsCategory/edit.jhtml?goodsCategory_id=" + treeNode.id;
	}else{
		url = base + "/admin/b2c/goodsCategory/edit.jhtml";
	}
	parent.rightFrame.location = url;
}
//新增节点
function addNode(newNodes, isSilent){
	var parentNode = zTree1.getNodeByParam("id", newNodes.parentId, null);
	zTree1.addNodes(parentNode, newNodes, isSilent);
}
//删除节点
function removeNode(id){
	var curNode = zTree1.getNodeByParam("id", id, null);
	zTree1.removeNode(curNode);
}
//更新节点
function updateNode(newNode){
	var curNode = zTree1.getNodeByParam("id", newNode.id, null);
	curNode.name=newNode.name;
	curNode.type=newNode.type;
	zTree1.updateNode(curNode);
}
